package xin.nick.interceptor;

import com.alibaba.fastjson2.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import xin.nick.constant.SystemConstants;
import xin.nick.entity.Result;

import java.net.URI;
import java.util.Optional;

/**
 * 处理统一返回响应信息
 * @author Nick
 */
@ControllerAdvice
public class UnifiedResponse implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        // 如果是api接口，则全部拦截包装
        String path = Optional.ofNullable(serverHttpRequest.getURI()).map(URI::getPath).orElse("");
        if (path.startsWith(SystemConstants.API_PATH)) {
            // 如果是 Result对象直接返回
            // 其他的对象都封装为Result
            if (o instanceof Result) {
                return o;
            } else {
                if (o instanceof String) {
                    return JSON.toJSONString(Result.success(o));
                }
                return Result.success(o);
            }
        } else {
            return o;
        }



    }
}
